{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "include_colab_link": true
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "view-in-github",
        "colab_type": "text"
      },
      "source": [
        "<a href=\"https://colab.research.google.com/github/nceder/qpb4e/blob/main/code/Chapter%2003/Chapter_03.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 3 The Quick Python overview\n",
        "\n",
        "This notebook contains all of the code examples shown in chapter 3 of The Quick Python Book. You can experiment with these - feel free to change values and see what happens.\n",
        "\n",
        "For full explanations of the these code snippets, please refer to chapter 3 of The Quick Python Book.\n",
        "\n",
        "# IMPORTANT!\n",
        "\n",
        "Run the cell below to load the data files needed for some of the code in this chapter."
      ],
      "metadata": {
        "id": "G1-s-iiNhYvv"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!wget https://raw.githubusercontent.com/nceder/qpb4e/main/code/Chapter%2003/shape.py  &> null  && echo Downloaded\n",
        "!wget https://raw.githubusercontent.com/nceder/qpb4e/main/code/Chapter%2003/wo.py &> null  && echo Downloaded\n",
        "\n",
        "!touch empty_file\n",
        "! echo \"This is myfile1.txt\" > myfile1.txt\n",
        "! echo \"This is myfile2.txt\" > myfile2.txt\n"
      ],
      "metadata": {
        "id": "B3D_aZeqf6Zl",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "aef14d12-8cad-4a9a-b744-7d91f750ebb1"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Downloaded\n",
            "Downloaded\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 3.2 Built-in data types\n",
        "##3.2.1 Numbers\n",
        "\n",
        "\n",
        "Python’s four number types are integers, floats, complex numbers, and Booleans:\n",
        "* Integers—1, –3, 42, 355, 888888888888888, –7777777777 (integers aren’t limited in size except by available memory)\n",
        "* Floats—3.0, 31e12, –6e-4\n",
        "* Complex numbers—3 + 2j, –4- 2j, 4.2 + 6.3j\n",
        "* Booleans—True, False\n",
        "\n",
        "You can manipulate them by using the arithmetic operators: + (addition), – (subtraction), * (multiplication), / (division), ** (exponentiation), and % (modulus).\n",
        "\n"
      ],
      "metadata": {
        "id": "fG-USLVrPdLF"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "The following examples use integers:"
      ],
      "metadata": {
        "id": "Y2SxvhMLdvYz"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x = 5 + 2 - 3 * 2\n",
        "x"
      ],
      "metadata": {
        "id": "CZbmJlwaJy8R",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "07782102-e4ab-41cb-9a09-76654ccd9ba2"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "1"
            ]
          },
          "metadata": {},
          "execution_count": 3
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "5 / 2"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "lKeovbS0F8nv",
        "outputId": "a1f1d56d-ab42-4f89-f8d6-3979962f95ff"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "2.5"
            ]
          },
          "metadata": {},
          "execution_count": 4
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "5 // 2"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "O55VIriZNXzJ",
        "outputId": "891d7c7b-26e1-4af9-a0dd-89ca64108c8b"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "2"
            ]
          },
          "metadata": {},
          "execution_count": 5
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "5 % 2"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ic-iasVPNbLU",
        "outputId": "e5a1c081-fd2a-4826-ac40-52d7934f7e80"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "1"
            ]
          },
          "metadata": {},
          "execution_count": 6
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "2 ** 8"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "jVGFs0A7H0cq",
        "outputId": "7df8b13d-7746-4540-deb9-ee6a454716a5"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "256"
            ]
          },
          "metadata": {},
          "execution_count": 7
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "1000000001 ** 3"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "U-sriHkbJYMX",
        "outputId": "7448e50a-68c7-423f-b152-2782116dd0ae"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "1000000003000000003000000001"
            ]
          },
          "metadata": {},
          "execution_count": 8
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "These examples work with floats, which are based on the doubles in C:"
      ],
      "metadata": {
        "id": "FcWFhmGRdq1U"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x = 4.3 ** 2.4\n",
        "x"
      ],
      "metadata": {
        "id": "LBlGsrtUH27E",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "1d25cf21-2e00-4e25-af9d-029ca191d940"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "33.13784737771648"
            ]
          },
          "metadata": {},
          "execution_count": 9
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "3.5e30 * 2.77e45"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5BN5CIN_U5qA",
        "outputId": "ede6130b-226c-4450-e83d-c905f420897a"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "9.695e+75"
            ]
          },
          "metadata": {},
          "execution_count": 10
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "1000000001.0 ** 3"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "jXzaVPy-U754",
        "outputId": "b1e64a77-ee67-4291-ee7d-78405006ecae"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "1.000000003e+27"
            ]
          },
          "metadata": {},
          "execution_count": 11
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "These examples use complex numbers:"
      ],
      "metadata": {
        "id": "xl7Ve8ozeKz-"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "(3+2j) ** (2+3j)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "SlkoDtoHU93Y",
        "outputId": "a5347ee8-5bfc-412d-ff99-7dbe7f8db1ac"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(0.6817665190890336-2.1207457766159625j)"
            ]
          },
          "metadata": {},
          "execution_count": 12
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x = (3+2j) * (4+9j)\n",
        "x"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "hAb61h6SVIc0",
        "outputId": "9497bc07-a3bf-4eb3-c414-fea16ac53af2"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(-6+35j)"
            ]
          },
          "metadata": {},
          "execution_count": 13
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x.real"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "_fORpUJRVLJI",
        "outputId": "ff7cfc64-c60d-4f28-abdd-d63d8f7dd2e3"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "-6.0"
            ]
          },
          "metadata": {},
          "execution_count": 14
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x.imag"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "EOV6c-sbVOEg",
        "outputId": "e6bbf77e-8a6c-4b7b-b363-3dd27e4bc326"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "35.0"
            ]
          },
          "metadata": {},
          "execution_count": 15
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Several built-in functions can operate on numbers. There are also the library module `cmath` (which contains functions for complex numbers) and the library module `math` (which contains functions for the other three types):"
      ],
      "metadata": {
        "id": "0HYinPSBeTr_"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "round(3.49)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "jDMROdVpVQG9",
        "outputId": "727b2ae5-b138-4ca1-e236-db0a17297645"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "3"
            ]
          },
          "metadata": {},
          "execution_count": 16
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import math\n",
        "math.ceil(3.49)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "8bLGaQS4VcRX",
        "outputId": "ba67c379-fbe7-41a7-cac6-14cf3c384309"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "4"
            ]
          },
          "metadata": {},
          "execution_count": 17
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "The following examples use Booleans:\n"
      ],
      "metadata": {
        "id": "qA3P7djAeb6d"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x = False\n",
        "x"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "LakfUvbrVc99",
        "outputId": "0a8ab154-03e8-427c-9e72-15c25f0b10c7"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "False"
            ]
          },
          "metadata": {},
          "execution_count": 18
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "not x\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "a6dR7WK8Vldw",
        "outputId": "e269c925-cd99-4832-e726-5598c61a7c05"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "True"
            ]
          },
          "metadata": {},
          "execution_count": 19
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "y = True * 2\n",
        "y"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "lkVSFAmSVn-c",
        "outputId": "20b5d7f2-59bd-4ade-e4fc-e455380a4ae9"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "2"
            ]
          },
          "metadata": {},
          "execution_count": 20
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.2.2 Lists\n",
        "\n",
        "Python has a powerful built-in list type:"
      ],
      "metadata": {
        "id": "v72-L_m8egrP"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "[]\n",
        "[1]\n",
        "[1, 2, 3, 4, 5, 6, 7, 8, 12]\n",
        "[1, \"two\", 3, 4.0, [\"a\", \"b\"], (5,6)]"
      ],
      "metadata": {
        "id": "BI_DhFofeswP",
        "outputId": "e4fa7b2f-2f88-4867-f2c8-d78100766fba",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[1, 'two', 3, 4.0, ['a', 'b'], (5, 6)]"
            ]
          },
          "metadata": {},
          "execution_count": 21
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "A list can be indexed from its front or back. You can also refer to a subsegment, or slice, of a list by using slice notation:"
      ],
      "metadata": {
        "id": "7lM0VCe2e6Gs"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x = [\"first\", \"second\", \"third\", \"fourth\"]\n",
        "x[0]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "id": "pqGrErzEVqU8",
        "outputId": "75fe0887-c97c-441e-a753-89569db455bf"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'first'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 22
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x[2]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "id": "nNmHcYz1V2gA",
        "outputId": "5bc896d1-7ea7-4c9c-a878-142590d17cc6"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'third'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 23
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x[-1]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "id": "XFRfNWMhV4aX",
        "outputId": "f756b61e-36e4-4e4f-9e7f-069e727becb4"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'fourth'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 24
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x[-2]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "id": "IfQbbPVKV7HU",
        "outputId": "2370ef7e-94e0-4878-931f-9e8550d8f485"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'third'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 25
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x[1:-1]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "dh_EfYYyV9ho",
        "outputId": "ae491af4-5623-48bd-cb6d-77628b63cb91"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['second', 'third']"
            ]
          },
          "metadata": {},
          "execution_count": 26
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x[0:3]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "UfL6j4SZV_bA",
        "outputId": "4b0de1c3-a730-43e9-8fb6-2e59941e8ed6"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['first', 'second', 'third']"
            ]
          },
          "metadata": {},
          "execution_count": 27
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x[-2:-1]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "AJOG1af_WA8G",
        "outputId": "dfdcec1b-852d-42f0-ad21-d35f43cc3e97"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['third']"
            ]
          },
          "metadata": {},
          "execution_count": 28
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x[:3]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VShFK31wWCzI",
        "outputId": "43c889b5-1262-4826-c455-1aab0164a521"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['first', 'second', 'third']"
            ]
          },
          "metadata": {},
          "execution_count": 29
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x[-2:]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "2hYBSqjoWEv_",
        "outputId": "41bbb809-2d0d-4bfe-a822-1e3fc8091e9b"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['third', 'fourth']"
            ]
          },
          "metadata": {},
          "execution_count": 30
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
        "x[1] = \"two\"\n",
        "x[8:9] = []\n",
        "x"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "GI_efk1VWIWo",
        "outputId": "63a727cc-e2ac-4b0e-9e1b-5d5cc17ef985"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[1, 'two', 3, 4, 5, 6, 7, 8]"
            ]
          },
          "metadata": {},
          "execution_count": 31
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x[5:7] = [6.0, 6.5, 7.0]\n",
        "x"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "mVqQZYo5WSjY",
        "outputId": "56494964-133d-4f0c-dc91-24ac4614275a"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[1, 'two', 3, 4, 5, 6.0, 6.5, 7.0, 8]"
            ]
          },
          "metadata": {},
          "execution_count": 32
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x[5:]"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "QoN8R5FyWU1U",
        "outputId": "26ac3c1c-dcf3-498d-ff43-752a82c52ff7"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[6.0, 6.5, 7.0, 8]"
            ]
          },
          "metadata": {},
          "execution_count": 33
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Some built-in functions (len, max, and min), some operators (in, +, and *), the del statement, and the list methods (append, count, extend, index, insert, pop, remove, reverse, and sort) operate on lists:"
      ],
      "metadata": {
        "id": "TB-c8GnXfCNP"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n",
        "len(x)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "BGp_j3UYWWqA",
        "outputId": "6cb63ff0-7ad8-4518-962e-fa093967259e"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "9"
            ]
          },
          "metadata": {},
          "execution_count": 34
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "[-1, 0] + x"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "UNSW0jwpYdpc",
        "outputId": "ee376007-ddfb-4063-fb7f-8b9fc8a2da36"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
            ]
          },
          "metadata": {},
          "execution_count": 35
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x.reverse()\n",
        "x"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "quB8b1rdYgdS",
        "outputId": "9c466f3c-6e36-4dea-8e83-020792c5f354"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[9, 8, 7, 6, 5, 4, 3, 2, 1]"
            ]
          },
          "metadata": {},
          "execution_count": 36
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.2.3 Tuples"
      ],
      "metadata": {
        "id": "_jt3B-YBYyNu"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "()\n",
        "(1,)\n",
        "(1, 2, 3, 4, 5, 6, 7, 8, 12)\n",
        "(1, \"two\", 3, 4.0, [\"a\", \"b\"], (5, 6))"
      ],
      "metadata": {
        "id": "rFcK511-fHHK",
        "outputId": "18ba762a-5440-4532-bfa6-2b1684f00a1f",
        "colab": {
          "base_uri": "https://localhost:8080/"
        }
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(1, 'two', 3, 4.0, ['a', 'b'], (5, 6))"
            ]
          },
          "metadata": {},
          "execution_count": 37
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "A list can be converted to a tuple by using the built-in function tuple:\n"
      ],
      "metadata": {
        "id": "_oL9pMmuZF8t"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x = [1, 2, 3, 4]\n",
        "tuple(x)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "CnJnJJu5YiUo",
        "outputId": "a671440b-b384-4e5e-dbb0-015039c7d639"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(1, 2, 3, 4)"
            ]
          },
          "metadata": {},
          "execution_count": 38
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Conversely, a tuple can be converted to a list by using the built-in function list:"
      ],
      "metadata": {
        "id": "6xgmVZL-ZUHD"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x = (1, 2, 3, 4)\n",
        "list(x)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VckW3-1xZQw3",
        "outputId": "dbea01a1-008c-4c2c-9d98-ddb012e40e6d"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[1, 2, 3, 4]"
            ]
          },
          "metadata": {},
          "execution_count": 39
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.2.4 Strings\n",
        "\n",
        "String processing is one of Python’s strengths. There are many options for delimiting strings:"
      ],
      "metadata": {
        "id": "F2pzHnEpaA4m"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "\"A string in double quotes can contain 'single quote' characters.\"\n",
        "'A string in single quotes can contain \"double quote\" characters.'\n",
        "'''\\tA string which starts with a tab; ends with a newline character.\\n'''\n",
        "\"\"\"This is a triple double quoted string - triple quoted strings (single\n",
        "   or double quoted) are only kind that can contain real newlines.\"\"\""
      ],
      "metadata": {
        "id": "JQNxp5XbfR53",
        "outputId": "4c562093-698a-49fe-fe16-213cfec3f521",
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 53
        }
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'This is a triple double quoted string - triple quoted strings (single\\n   or double quoted) are only kind that can contain real newlines.'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 40
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Strings have several methods to work with their contents..."
      ],
      "metadata": {
        "id": "avE24bZCaYy7"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x = \"live and     let \\t   \\tlive\"\n",
        "x.split()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "A328ZaWuZZyP",
        "outputId": "5db988e7-2b01-40c5-c054-7fd11d59db75"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "['live', 'and', 'let', 'live']"
            ]
          },
          "metadata": {},
          "execution_count": 41
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x.replace(\"    let \\t   \\tlive\", \"enjoy life\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "id": "daRy-GgMaKlE",
        "outputId": "e44d0ae3-ef62-4e3a-88a2-68fafea47be4"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'live and enjoy life'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 42
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        " The `re` library module also contains functions for working with strings:"
      ],
      "metadata": {
        "id": "LY5Wpg7ofiHX"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import re\n",
        "regexpr = re.compile(r\"[\\t ]+\")\n",
        "regexpr.sub(\" \", x)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "id": "ufQV9sVYaMu8",
        "outputId": "3575b8c1-4ff7-461c-f65d-c91a14a72455"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'live and let live'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 43
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "The print function outputs strings. Other Python data types can be easily converted to strings and formatted:"
      ],
      "metadata": {
        "id": "-WNemPy_adk1"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "e = 2.718\n",
        "x = [1, \"two\", 3, 4.0, [\"a\", \"b\"], (5, 6)]\n",
        "print(\"The constant e is:\", e, \"and the list x is:\", x)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "hN_Q7GSMaO2o",
        "outputId": "ae18da87-eca4-42ee-c09d-d5c007f3ad66"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "The constant e is: 2.718 and the list x is: [1, 'two', 3, 4.0, ['a', 'b'], (5, 6)]\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Objects are automatically converted to string representations for printing #1.\n",
        "\n",
        "Placing an `f` in front of a string  #2 inserts the values of variables or expressions in `{}` into the string."
      ],
      "metadata": {
        "id": "21OfbhlCb6zJ"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "print(f\"the value of e is: {e}\")                 #2"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "HSS6Vmr1angH",
        "outputId": "2d1f6a8a-07e9-4dfb-e43b-1e6f4279765e"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "the value of e is: 2.718\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.2.5 Dictionaries"
      ],
      "metadata": {
        "id": "AiUQaIx6cQQK"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "Keys must be of an immutable type #1, including numbers, strings, and tuples. Values can be any kind of object, including mutable types such as lists and dictionaries."
      ],
      "metadata": {
        "id": "dubAF9AFctdM"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x = {1: \"one\", 2: \"two\"}\n",
        "x[\"first\"] = \"one\"         #A\n",
        "x[(\"Delorme\", \"Ryan\", 1995)] = (1, 2, 3)   #1\n",
        "list(x.keys())"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Ir3m0LZCarNf",
        "outputId": "e65ead72-5b22-4660-c129-93ba228cd4f3"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "[1, 2, 'first', ('Delorme', 'Ryan', 1995)]"
            ]
          },
          "metadata": {},
          "execution_count": 46
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "If you try to access the value of a key that isn’t in the dictionary, a `KeyError` exception is raised. To avoid this error, the dictionary method `get` #2 optionally returns a user-definable value when a key isn’t in a dictionary."
      ],
      "metadata": {
        "id": "6OJQUwpQc8Sk"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x.get(1, \"not available\")"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "id": "vC6-PFuKcghk",
        "outputId": "abf48371-8a2f-409c-9046-61d0eceb3520"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'one'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 47
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "x.get(4, \"not available\")      #2"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 35
        },
        "id": "Jzg7POF4dEV1",
        "outputId": "d7c21adb-f17e-4422-9829-3696641b0f92"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "'not available'"
            ],
            "application/vnd.google.colaboratory.intrinsic+json": {
              "type": "string"
            }
          },
          "metadata": {},
          "execution_count": 48
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.2.6 Sets, frozensets\n",
        "\n",
        " A set in Python is an unordered collection of objects, used in situations where membership and uniqueness in the set are important. Frozensets are similar to sets, but once created are immutable."
      ],
      "metadata": {
        "id": "EtKGQzikhLaX"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x = set([1, 2, 3, 1, 3, 5])\n",
        "x"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5B2JpJb1dIs0",
        "outputId": "40eb003f-8797-4244-e36f-b231b956309e"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{1, 2, 3, 5}"
            ]
          },
          "metadata": {},
          "execution_count": 49
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "1 in x\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ZsZtRJWuhhcH",
        "outputId": "c81d96ff-6557-4bdc-81f1-eb29d7011852"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "True"
            ]
          },
          "metadata": {},
          "execution_count": 50
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "4 in x"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "VEoPc0E7hkUI",
        "outputId": "f239ce0e-399d-46a5-ead6-2de94a8c45aa"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "False"
            ]
          },
          "metadata": {},
          "execution_count": 51
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.2.7 File objects\n",
        "\n",
        "A file is accessed through a Python file object:"
      ],
      "metadata": {
        "id": "usi1-G9khwln"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "f = open(\"myfile\", \"w\")\n",
        "f.write(\"First line with necessary newline character\\n\")\n",
        "f.write(\"Second line to write to the file\\n\")\n",
        "f.close()\n",
        "f = open(\"myfile\", \"r\")\n",
        "line1 = f.readline()\n",
        "line2 = f.readline()\n",
        "f.close()\n",
        "print(line1, line2)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "NONkf868hoXo",
        "outputId": "854f6aa5-e05b-4495-e0d8-9d0b40e9020a"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "First line with necessary newline character\n",
            " Second line to write to the file\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "import os                               #3\n",
        "directory = os.getcwd()\n",
        "print(directory)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "y9RGDH2ciBvc",
        "outputId": "61a81286-2e3c-48a9-888a-6969c6323969"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "/content\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "filename = os.path.join(directory, \"myfile\")                                          #5\n",
        "print(filename)\n",
        "f = open(filename, \"r\")\n",
        "print(f.readline())\n",
        "f.close()\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "7-HxPICHihup",
        "outputId": "74a8def3-3ea1-4269-f3fa-c17194c3fac9"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "/content/myfile\n",
            "First line with necessary newline character\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 3.4 Control flow structures\n",
        "## 3.4.2 if-elif-else statement\n",
        "\n",
        "The block of code after the first `True` condition (of an `if` or an `elif`) is executed. If none of the conditions is `True`, the block of code after the `else` is executed:"
      ],
      "metadata": {
        "id": "UvFwBu1Ei9z2"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "x = 5\n",
        "if x < 5:\n",
        "    y = -1\n",
        "    z = 5\n",
        "elif x > 5:\n",
        "    y = 1\n",
        "    z = 11\n",
        "else:\n",
        "    y = 0\n",
        "    z = 10\n",
        "print(x, y, z)\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ueunjjeDjDQp",
        "outputId": "b814f192-0652-4383-8300-b0da2951f9ea"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "5 0 10\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.4.3 Structural pattern matching\n",
        "\n",
        "Versions of Python from 3.10 have the match statement with allows for flexible and powerful pattern matching,"
      ],
      "metadata": {
        "id": "SmlMV5q9jl3t"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# point is an (x, y) tuple\n",
        "point = (1, 2)\n",
        "\n",
        "match point:\n",
        "    case (0, 0):\n",
        "        print(\"Origin\")\n",
        "    case (0, y):\n",
        "        print(f\"Y={y}\")\n",
        "    case (x, 0):\n",
        "        print(f\"X={x}\")\n",
        "    case (x, y):\n",
        "        print(f\"X={x}, Y={y}\")\n",
        "    case _:\n",
        "        raise ValueError(\"Not a point\")\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "Puhd7y_xjFOQ",
        "outputId": "34b5e2a2-4753-4523-9037-063ef3472807"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "X=1, Y=2\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "\n",
        "## 3.4.4 The while loop\n",
        "\n",
        "The `while` loop is executed as long as the condition (which here is `x > y`) is `True`:\n"
      ],
      "metadata": {
        "id": "ToXJPu3hjwVf"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "u, v, x, y = 0, 0, 100, 30    #A\n",
        "while x > y:           #B\n",
        "    u = u + y          #B\n",
        "    x = x - y          #B\n",
        "    if x < y + 2:      #B\n",
        "        v = v + x      #B\n",
        "        x = 0          #B\n",
        "    else:              #B\n",
        "        v = v + y + 2  #B\n",
        "        x = x - y - 2  #B\n",
        "    print(f\"{u=} {v=}\")  #C\n",
        "print(u, v)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "OnIJzNw-Eb3o",
        "outputId": "0b9c7949-edbf-4cdf-cafa-d5782dc96f6b"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "u=30 v=32\n",
            "u=60 v=40\n",
            "60 40\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.4.5 The for loop\n",
        "\n",
        "The for loop is simple but powerful because it’s possible to iterate over any iterable type, such as a list or tuple. U"
      ],
      "metadata": {
        "id": "2zwVR_83kUyo"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "item_list = [3, \"string1\", 23, 14.0, \"string2\", 49, 64, 70]\n",
        "for x in item_list:\n",
        "    if not isinstance(x, int):\n",
        "        continue\n",
        "    if not x % 7:\n",
        "        print(\"found an integer divisible by seven: %d\" % x)\n",
        "        break\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "s8Ti9ORoj-x6",
        "outputId": "1ff5a319-0bb1-4855-a67b-2d6bce2e7dba"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "found an integer divisible by seven: 49\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.4.6 Function definition\n",
        "\n",
        "Python provides flexible mechanisms for passing arguments to functions:"
      ],
      "metadata": {
        "id": "WU8MFG6bkkvs"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def funct1(x, y, z):\n",
        "    value = x + 2*y + z**2\n",
        "    if value > 0:\n",
        "        return x + 2*y + z**2\n",
        "    else:\n",
        "        return 0\n",
        "\n",
        "u, v = 3, 4\n",
        "funct1(u, v, 2)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "DIGQ0vsMkcn8",
        "outputId": "215ec717-770c-45b8-a220-de3f0c9acf6e"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "15"
            ]
          },
          "metadata": {},
          "execution_count": 59
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Function arguments can be entered either by position or by name (keyword). Here, z and y are entered by name #3"
      ],
      "metadata": {
        "id": "cUQDY_k8lU3l"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "funct1(u, z=v, y=2)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "00ggo_eEk2Kg",
        "outputId": "30b4495a-3172-4a0a-8f8e-6ed812ee52b7"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "23"
            ]
          },
          "metadata": {},
          "execution_count": 60
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        " Function parameters can be defined with defaults that are used if a function call leaves them out #4."
      ],
      "metadata": {
        "id": "U0lyuUsrldOk"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def funct2(x, y=1, z=1):\n",
        "    return x + 2 * y + z ** 2\n",
        "\n",
        "funct2(3, z=4)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "w7m6K5FRk53Y",
        "outputId": "54dd4fcb-34bd-4d61-ab18-e204aff1f415"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "21"
            ]
          },
          "metadata": {},
          "execution_count": 61
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "A special parameter can be defined that collects all extra positional arguments in a function call into a tuple #5."
      ],
      "metadata": {
        "id": "298H6S5MlgXL"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def funct3(x, y=1, z=1, *tup):\n",
        "    print((x, y, z) + tup)\n",
        "\n",
        "funct3(2)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "5QyDC0zBk84Y",
        "outputId": "e66a87f7-ca91-418e-b18a-855f7ca009e8"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "(2, 1, 1)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "funct3(1, 2, 3, 4, 5, 6, 7, 8, 9)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "m2fqxWL8lIFN",
        "outputId": "a688a2eb-d6cd-447f-dfd1-23642cd1a445"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "(1, 2, 3, 4, 5, 6, 7, 8, 9)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Likewise, a special parameter can be defined that collects all extra keyword arguments in a function call into a dictionary #6."
      ],
      "metadata": {
        "id": "E1fij6galirh"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def funct4(x, y=1, z=1, **kwargs):\n",
        "    print(x, y, z, kwargs)\n",
        "funct4(1, 2, m=5, n=9, z=3)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ZTYwu7shlLeM",
        "outputId": "b249472e-3b3f-43aa-e61e-8a1ebb9318d8"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "1 2 3 {'m': 5, 'n': 9}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.4.7 Exceptions\n",
        "\n",
        "Exceptions (errors) can be caught and handled by using the `try-except-else-finally` compound statement. This statement can also catch and handle exceptions you define and raise yourself."
      ],
      "metadata": {
        "id": "WuukV_xPcOp3"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "class EmptyFileError(Exception):     #A\n",
        "    pass\n",
        "file_names = [\"myfile1.txt\", \"non_existent\", \"empty_file\", \"myfile2.txt\"]\n",
        "for file_name in file_names:\n",
        "    try:                             #B\n",
        "        file = open(file_name, 'r')\n",
        "        line = file.readline()          #C\n",
        "        if line == \"\":\n",
        "            file.close()\n",
        "            raise EmptyFileError(\"{file_name}: is empty\")      #D\n",
        "    except IOError as error:\n",
        "        print(f\"{file_name}: could not be opened: {error.strerror}\")\n",
        "    except EmptyFileError as error:\n",
        "        print(error)\n",
        "    else:                             #E\n",
        "        print(f\"{file_name}: {line}\")\n",
        "    finally:\n",
        "        print(\"Done processing\", file_name)                       #F"
      ],
      "metadata": {
        "id": "etISj5_2lN2U",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "7459dde0-60a1-4ac8-abe5-2cbfdd3521c4"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "myfile1.txt: This is myfile1.txt\n",
            "\n",
            "Done processing myfile1.txt\n",
            "non_existent: could not be opened: No such file or directory\n",
            "Done processing non_existent\n",
            "{file_name}: is empty\n",
            "Done processing empty_file\n",
            "myfile2.txt: This is myfile2.txt\n",
            "\n",
            "Done processing myfile2.txt\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "## 3.4.8 Context handling using the `with` keyword\n",
        "\n",
        "A more streamlined way of encapsulating the try-except-finally pattern is to use the with keyword and a context manager. This example shows opening and reading a file by using `with` and a context manager."
      ],
      "metadata": {
        "id": "iu5RSkxHcQNq"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "filename = \"myfile1.txt\"\n",
        "with open(filename, \"r\") as file:\n",
        "    for line in file:\n",
        "        print(line)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "AxjVvseobz-l",
        "outputId": "01f2ee47-e243-4e37-fa3c-de08d7f9aa87"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "This is myfile1.txt\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "That code is equivalent to this code:"
      ],
      "metadata": {
        "id": "_iu27UgUcYkl"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "filename = \"myfile1.txt\"\n",
        "try:\n",
        "    file = open(filename, \"r\")\n",
        "    for line in file:\n",
        "        print(line)\n",
        "except Exception as e:\n",
        "    raise e\n",
        "finally:\n",
        "    file.close()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "U0C7x2iicVXD",
        "outputId": "aa49173b-e2fb-4dd8-c627-e8884090591e"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "This is myfile1.txt\n",
            "\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# 3.5 Module creation\n",
        "\n",
        "It’s easy to create your own modules, which can be imported and used in the same way as Python’s built-in library modules. The example in this listing is a deliberately oversimplified module with one function that prompts the user to enter a filename and determines the number of times that words occur in this file."
      ],
      "metadata": {
        "id": "5q5T0jN0cvvA"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "\"\"\"wo module. Contains function: words_occur()\"\"\"\n",
        "# interface functions\n",
        "def words_occur():\n",
        "    \"\"\"words_occur() - count the occurrences of words in a file.\"\"\"\n",
        "    # Prompt user for the name of the file to use.\n",
        "    file_name = input(\"Enter the name of the file: \")\n",
        "    # Open the file, read it and store its words in a list.\n",
        "    file = open(file_name, 'r')\n",
        "    word_list = file.read().split()\n",
        "    file.close()\n",
        "    # Count the number of occurrences of each word in the file.\n",
        "    occurs_dict = {}\n",
        "    for word in word_list:\n",
        "        # increment the occurrences count for this word\n",
        "        occurs_dict[word] = occurs_dict.get(word, 0) + 1\n",
        "    # Print out the results.\n",
        "    print(f\"File {file_name} has {len(word_list)} words ({len(occurs_dict)} are unique)\")\n",
        "    print(occurs_dict)\n",
        "if __name__ == '__main__':\n",
        "    words_occur()\n"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "vqAl4TMkcdrD",
        "outputId": "de9d9dd3-f4b9-4505-b336-b9827f49083d"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Enter the name of the file: myfile1.txt\n",
            "File myfile1.txt has 3 words (3 are unique)\n",
            "{'This': 1, 'is': 1, 'myfile1.txt': 1}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "If a file is in the current directory or in one of the directories on the module search path, which can be found in sys.path, it can be imported like any of the built-in library modules by using the import statement:\n"
      ],
      "metadata": {
        "id": "ogOmddBreirr"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import wo\n",
        "wo.words_occur()"
      ],
      "metadata": {
        "id": "hY8Z_V59dMH7",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "864fa1b0-e7e7-4978-f15d-fec6b270c275"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Enter the name of the file: wo.py\n",
            "File wo.py has 117 words (81 are unique)\n",
            "{'\"\"\"wo': 1, 'module.': 1, 'Contains': 1, 'function:': 1, 'words_occur()\"\"\"': 1, '#1': 1, '#': 6, 'interface': 1, 'functions': 1, '#2': 1, 'def': 1, 'words_occur():': 1, '\"\"\"words_occur()': 1, '-': 1, 'count': 2, 'the': 10, 'occurrences': 3, 'of': 5, 'words': 3, 'in': 4, 'a': 2, 'file.\"\"\"': 1, 'Prompt': 1, 'user': 1, 'for': 3, 'name': 2, 'file': 1, 'to': 1, 'use.': 1, 'file_name': 1, '=': 5, 'input(\"Enter': 1, 'file:': 1, '\")': 1, 'Open': 1, 'file,': 1, 'read': 1, 'it': 1, 'and': 1, 'store': 1, 'its': 1, 'list.': 1, 'f': 1, 'open(file_name,': 1, \"'r')\": 1, 'word_list': 1, 'f.read().split()': 1, '#3': 1, 'f.close()': 1, 'Count': 1, 'number': 1, 'each': 1, 'word': 3, 'file.': 1, 'occurs_dict': 1, '{}': 1, 'word_list:': 1, 'increment': 1, 'this': 1, 'occurs_dict[word]': 1, 'occurs_dict.get(word,': 1, '0)': 1, '+': 1, '1': 1, 'Print': 1, 'out': 1, 'results.': 1, 'print(f\"File': 1, '{file_name}': 1, 'has': 1, '{len(word_list)}': 1, '({len(occurs_dict)}': 1, 'are': 1, 'unique)\")': 1, 'print(occurs_dict)': 1, 'if': 1, '__name__': 1, '==': 1, \"'__main__':\": 1, '#4': 1, 'words_occur()': 1}\n"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "Note that if you change the file wo.py on disk, import won’t bring your changes into the same interactive session. You use the reload function from the imp library in this situation:\n"
      ],
      "metadata": {
        "id": "m9g3fqt6eoM9"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import importlib as imp\n",
        "imp.reload(wo)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "IDqtNOPbesA8",
        "outputId": "8aaa9f10-be8a-4294-ac25-7ad8133bf8c9"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "<module 'wo' from '/content/wo.py'>"
            ]
          },
          "metadata": {},
          "execution_count": 72
        }
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "#3.4 Object oriented programming\n",
        "\n",
        "Python provides full support for OOP. Listing 3.4 is an example that might be the start of a simple shapes module for a drawing program."
      ],
      "metadata": {
        "id": "WjqpzU_GfE5b"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "### Listing 3.4 File shape.py\n"
      ],
      "metadata": {
        "id": "K8Ff6b0RfI7-"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "\"\"\"shape module. Contains classes Shape, Square and Circle\"\"\"\n",
        "class Shape:\n",
        "    \"\"\"Shape class: has method move\"\"\"\n",
        "    def __init__(self, x, y):\n",
        "        self.x = x\n",
        "        self.y = y\n",
        "    def move(self, deltaX, deltaY):\n",
        "        self.x = self.x + deltaX\n",
        "        self.y = self.y + deltaY\n",
        "class Square(Shape):\n",
        "    \"\"\"Square Class:inherits from Shape\"\"\"\n",
        "    def __init__(self, side=1, x=0, y=0):\n",
        "        Shape.__init__(self, x, y)\n",
        "        self.side = side\n",
        "class Circle(Shape):\n",
        "    \"\"\"Circle Class: inherits from Shape and has method area\"\"\"\n",
        "    pi = 3.14159\n",
        "    def __init__(self, r=1, x=0, y=0):\n",
        "        Shape.__init__(self, x, y)\n",
        "        self.radius = r\n",
        "    def area(self):\n",
        "        \"\"\"Circle area method: returns the area of the circle.\"\"\"\n",
        "        return self.radius * self.radius * self.pi\n",
        "    def __str__(self):\n",
        "        return \"Circle of radius %s at coordinates (%d, %d)\"\\\n",
        "               % (self.radius, self.x, self.y)\n"
      ],
      "metadata": {
        "id": "E6zUPdjNevCS"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "import shape\n",
        "c1 = shape.Circle()\n",
        "c2 = shape.Circle(5, 15, 20)\n",
        "print(c1)\n",
        "\n",
        "print(c2)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "KzLtDjP7e-Iv",
        "outputId": "958e708e-ff13-40dc-f342-840d886b6033"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Circle of radius 1 at (0, 0)\n",
            "Circle of radius 5 at (15, 20)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "c2.area()"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "G1fBe5j_frPj",
        "outputId": "1b9fc616-5cca-4863-a7f7-7b59e545bba6"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "78.53975"
            ]
          },
          "metadata": {},
          "execution_count": 76
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "c2.move(5,6)\n",
        "print(c2)"
      ],
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "ekWNnIMtf4LC",
        "outputId": "b9ad702b-ac2c-4d78-f39b-552bd00fff4b"
      },
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "Circle of radius 5 at (20, 26)\n"
          ]
        }
      ]
    },
    {
      "cell_type": "code",
      "source": [],
      "metadata": {
        "id": "4HEL-0jpMNDf"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}
